import java.util.ArrayList;

public class LeetCode202_HappyNum {
    public boolean isHappy(int n) {
        ArrayList<Integer> list = new ArrayList<>();
        while (true) {
            int num = 0;
            int x = n;
            list.add(x);
            while (x != 0) {
                num += (x % 10) * (x % 10);
                x /= 10;
            }
            if (num == 1) {
                return true;
            }
            if (list.contains(num)) {
                return false;
            }
            n = num;
        }
    }

    public boolean isHappy2(int n) {//快慢指针思想
        int x = n;//慢
        int y = n;//快

        while (true) {
            int slow = 0;
            int fast = 0;
            slow = bitSum(x);
            y = bitSum(y);
            fast = bitSum(y);
            if (fast == slow && fast == 1) {
                return true;
            }
            if(fast == slow && fast != 1) {
                return false;
            }
            x = slow;
            y = fast;
        }

    }

    public int bitSum(int n) {//求每一位平方的和
        int sum = 0;
        while (n != 0) {
            sum += (n % 10) * (n % 10);
            n /= 10;
        }
        return sum;
    }
}
